<?php
/**
 * @package site
 */
class PairingBonus extends DataObject implements PermissionProvider {
    private static $singular_name = "Pairing Bonus";
    private static $plural_name = "Pairing Bonuses";

    private static $payout_table = array(
        'level1' => array(
            'percentage' => 0.07,
            'max_payout' => 500
        ),
        'level2' => array(
            'percentage' => 0.08,
            'max_payout' => 1000
        ),
        'level3' => array(
            'percentage' => 0.09,
            'max_payout' => 3000
        ),
        'level4' => array(
            'percentage' => 0.1,
            'max_payout' => 5000
        ),
        'level5' => array(
            'percentage' => 0.11,
            'max_payout' => 10000
        ),
        'level6' => array(
            'percentage' => 0.12,
            'max_payout' => 20000
        )
    );

    private static $db = array(
        'Percentage' => 'Percentage',
        'MaxPayout' => 'Currency',
        'BV' => 'Int',
        'Debit' => 'Currency',
        'Credit' => 'Currency',
        'ForwardBalance' => 'Currency',
        'Remark' => 'Varchar(250)'
    );

    private static $has_one = array(
        'Batch' => 'BonusBatch',
        'Member' => 'Member',
        'Group' => 'Group'
    );

    private static $many_many = array(
		'BonusAccounts' => 'BonusAccount',
		'ProductAccounts' => 'ProductAccount',
        'TradeCoinAccounts' => 'TradeCoinAccount',
        'UpgradeAccounts' => 'UpgradeAccount'
    );

    private static $default_sort = "Created DESC, ID DESC";

    private static $searchable_fields = array(
        'Batch.Code',
        'Member.FirstName',
        'Member.Surname',
        'Member.Username',
        'GroupID',
        'Percentage',
        'MaxPayout',
        'BV',
        'Remark'
    );

    private static $summary_fields = array(
        'Batch.Code',
        'Member.Username',
        'Member.Name',
        'Description',
        'AmountText',
        'ForwardBalance',
        'Remark'
    );

    private static $casting = array('Balance' => 'Currency');

    public function fieldLabels($includerelations = true) {
        $labels = parent::fieldLabels($includerelations);

        $labels['Description'] = _t('PairingBonus.DESCRIPTION', 'Description');
        $labels['Percentage'] = _t('PairingBonus.PERCENTAGE', 'Percentage');
        $labels['Percentage.Nice'] = _t('PairingBonus.PERCENTAGE', 'Percentage');
        $labels['MaxPayout'] = _t('PairingBonus.MAX_PAYOUT', 'Max Payout');
        $labels['BV'] = _t('PairingBonus.BV', 'BV');
        $labels['Debit'] = _t('PairingBonus.DEBIT', 'Debit');
        $labels['Credit'] = _t('PairingBonus.CREDIT', 'Credit');
        $labels['AmountText'] = _t('PairingBonus.AMOUNT', 'Amount');
        $labels['ForwardBalance'] = _t('PairingBonus.BALANCE', 'Balance');
        $labels['Remark'] = _t('PairingBonus.REMARK', 'Remark');
        $labels['Batch'] = _t('PairingBonus.BATCH', 'Batch');
        $labels['Batch.Code'] = _t('PairingBonus.BATCH', 'Batch');
        $labels['Group'] = _t('PairingBonus.GROUP', 'Group');
        $labels['GroupID'] = _t('PairingBonus.GROUP', 'Group');
        $labels['BonusAccounts'] = _t('PairingBonus.BONUS_ACCOUNT', 'E-Bonus Accounts');
        $labels['ProductAccounts'] = _t('PairingBonus.PRODUCT_ACCOUNT', 'E-Product Accounts');
		$labels['TradeCoinAccounts'] = _t('PairingBonus.TRADE_COIN_ACCOUNT', 'Trade-Coin Accounts');
		$labels['UpgradeAccounts'] = _t('PairingBonus.UPGRADE_ACCOUNT', 'E-Upgrade Accounts');
        $labels['Member.Username'] = _t('PairingBonus.USERNAME', 'Username');
        $labels['Member'] = _t('PairingBonus.NAME', 'Name');
        $labels['Member.Name'] = _t('PairingBonus.NAME', 'Name');
        $labels['Member.FirstName'] = _t('PairingBonus.FIRSTNAME', 'First Name');
        $labels['Member.Surname'] = _t('PairingBonus.SURNAME', 'Surname');
        return $labels;
    }

    function onBeforeWrite() {
        parent::onBeforeWrite();
        $this->setField('ForwardBalance', $this->getBalance() + $this->Credit - $this->Debit);
    }

    function onAfterWrite() {
        parent::onAfterWrite();
		if(!$this->Member()->NoPairingPayout){
	        if($this->Credit > 0) {
	            if(!$count = $this->BonusAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Description)->filter('Reference', $this->Batch()->Code)->filter('Credit:GreaterThan', 0)->count()) {
	                $statement_data = array(
	                    'Type' => 'Bonus',
	                    'Credit' => $this->Credit * 0.7,
	                    'Reference' => $this->Batch()->Code,
	                    'Description' => $this->Description
	                );
					
					if($this->Member()->IsExceedPayout){
						$statement_data['Credit'] = $statement_data['Credit'] * 0.5;
						
						$id = UpgradeAccount::create_statement($statement_data, $this->MemberID);
						$this->UpgradeAccounts()->add($id);
					}
	
	                $id = BonusAccount::create_statement($statement_data, $this->MemberID);
	                $this->BonusAccounts()->add($id);
	            }
	
	            if(!$count = $this->ProductAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Description)->filter('Reference', $this->Batch()->Code)->filter('Credit:GreaterThan', 0)->count()) {
	                $statement_data = array(
	                    'Type' => 'Bonus',
	                    'Credit' => $this->Credit * 0.1,
	                    'Reference' => $this->Batch()->Code,
	                    'Description' => $this->Description
	                );
	                $id = ProductAccount::create_statement($statement_data, $this->MemberID);
	                $this->ProductAccounts()->add($id);
	            }
	
				if(!$count = $this->TradeCoinAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Description)->filter('Reference', $this->Batch()->Code)->filter('Credit:GreaterThan', 0)->count()) {
	                $statement_data = array(
	                    'Type' => 'Bonus',
	                    'Credit' => $this->Credit * 0.2,
	                    'Reference' => $this->Batch()->Code,
	                    'Description' => $this->Description
	                );
	                $id = TradeCoinAccount::create_statement($statement_data, $this->MemberID);
	                $this->TradeCoinAccounts()->add($id);
	            }
	        }
	
	        if($this->Debit > 0) {
	            $statement = $this->BonusAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Description)->filter('Reference', $this->Batch()->Code)->filter('Credit:GreaterThan', 0);
	            if($statement->count() > $this->BonusAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Remark)->filter('Reference', $this->Batch()->Code)->filter('Debit:GreaterThan', 0)->count()) {
	                $statement_data = array(
	                    'Type' => $statement->Type,
	                    'Debit' => $statement->Credit,
	                    'Reference' => $statement->Reference,
	                    'Description' => $this->Remark ? $this->Remark : sprintf('Deduct - %s', $statement->Description)
	                );
	                $id = BonusAccount::create_statement($statement_data, $statement->MemberID);
	                $this->BonusAccounts()->add($id);
	            }
				
				$statement = $this->UpgradeAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Description)->filter('Reference', $this->Batch()->Code)->filter('Credit:GreaterThan', 0);
	            if($statement->count() > $this->UpgradeAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Remark)->filter('Reference', $this->Batch()->Code)->filter('Debit:GreaterThan', 0)->count()) {
	                $statement_data = array(
	                    'Type' => $statement->Type,
	                    'Debit' => $statement->Credit,
	                    'Reference' => $statement->Reference,
	                    'Description' => $this->Remark ? $this->Remark : sprintf('Deduct - %s', $statement->Description)
	                );
	                $id = UpgradeAccount::create_statement($statement_data, $statement->MemberID);
	                $this->UpgradeAccounts()->add($id);
	            }
	
	            $statement = $this->ProductAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Description)->filter('Reference', $this->Batch()->Code)->filter('Credit:GreaterThan', 0);
	            if($statement->count() > $this->ProductAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Remark)->filter('Reference', $this->Batch()->Code)->filter('Debit:GreaterThan', 0)->count()) {
	                $statement_data = array(
	                    'Type' => $statement->Type,
	                    'Debit' => $statement->Credit,
	                    'Reference' => $statement->Reference,
	                    'Description' => $this->Remark ? $this->Remark : sprintf('Deduct - %s', $statement->Description)
	                );
	                $id = ProductAccount::create_statement($statement_data, $statement->MemberID);
	                $this->ProductAccounts()->add($id);
	            }
				
				$statement = $this->TradeCoinAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Description)->filter('Reference', $this->Batch()->Code)->filter('Credit:GreaterThan', 0);
	            if($statement->count() > $this->TradeCoinAccounts()->filter('Type', 'Bonus')->filter('Description', $this->Remark)->filter('Reference', $this->Batch()->Code)->filter('Debit:GreaterThan', 0)->count()) {
	                $statement_data = array(
	                    'Type' => $statement->Type,
	                    'Debit' => $statement->Credit,
	                    'Reference' => $statement->Reference,
	                    'Description' => $this->Remark ? $this->Remark : sprintf('Deduct - %s', $statement->Description)
	                );
	                $id = TradeCoinAccount::create_statement($statement_data, $statement->MemberID);
	                $this->TradeCoinAccounts()->add($id);
	            }
	        }
        }
    }

    function getBalance() {
        return PairingBonus::get()->filter('MemberID', $this->MemberID)->sum('Credit') - PairingBonus::get()->filter('MemberID', $this->MemberID)->sum('Debit');
    }

    function getDescription() {
    	return _t('PairingBonus.SHOW_DESCRIPTION', 'PAIRING BONUS ON {batch}', '', array('batch' => $this->Batch()->dbObject('Date')->Nice()));
    }

    function getAmountText() {
        if($this->Credit == $this->Debit) {
            return DBField::create_field('Double', 0)->Nice();
        } else if($this->Credit > 0) {
            return sprintf('%s(+)', DBField::create_field('Double', $this->Credit)->Nice());
        } else {
            return sprintf('%s(-)', DBField::create_field('Double', $this->Debit)->Nice());
        }
    }

    function canView($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('VIEW_PairingBonus');
    }

    function canEdit($member = false) {
        return false;
    }

    function canDelete($member = false) {
        return false;
    }

    function canCreate($member = false) {
        return false;
    }

    public function providePermissions() {
        return array(
            'VIEW_PairingBonus' => array(
                'name' => _t('PairingBonus.PERMISSION_VIEW', 'Allow view access right'),
                'category' => _t('PairingBonus.PERMISSIONS_CATEGORY', 'Pairing Bonus')
            )
        );
    }

}
?>
